#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from config import etc
from utils import log
from utils.file_util import get_300_size_imglink
from utils.session_base import ApiHost
from utils.session_mc import BaseHandler
from controls import data_message_system_content_mysql
from controls import data_message_system_status_mysql
from controls import data_message_system_mysql
from controls import data_message_user_mysql
from controls import data_message_pet_mysql
from controls import data_user_brief_mysql
from controls import data_user_base_mysql
from controls import data_topic_note_like_mysql
from controls import data_topic_note_img_mysql
from controls import data_topic_title_mysql
from controls import data_img_base_mysql
from controls import data_topic_note_mysql

# class SystemMessageHandler(BaseHandler):
#     @ApiHost
#     def post(self):
#         userid = self.ss_user['userid']
#         begin = self.ss_params.get('begin', 0)
#         limit = self.ss_params.get('limit', 20)
#
#         if begin and limit is None:
#             log.w('params fetching error')
#             res = {'idx': self.ss_idx, 'ret': 1, 'msg': etc.err_500, 'res': {}}
#             self.write(json.dumps(res))
#             self.finish()
#             return
#
#         try:
#             messages = data_message_system_mysql\
#                 .get_message_system_by_userid(userid, begin, limit)
#
#             ret = {
#                 'idx': self.ss_idx,
#                 'ret': 0,
#                 'res': messages,
#                 'msg': "ok"
#             }
#
#             self.write(json.dumps(ret))
#             self.finish()
#             return
#
#         except Exception as e:
#             log.exp(e)
#             self._generate_res(1, etc.err_500, 'system_mes')
#             return

class ListSystemMessageHandler(BaseHandler):
    @ApiHost
    def post(self, *args, **kwargs):
        userid = self.current_user.get('userid', None)
        begin = self.ss_params.get('begin', 0)
        limit = self.ss_params.get('limit', 20)

        if userid is None:
            log.w('params fetching error')
            res = {'idx': self.ss_idx, 'ret': 1, 'msg': etc.err_500, 'res': {}}
            self.write(json.dumps(res))
            self.finish()
            return

        try:
            regtime = data_user_base_mysql.get_user_base_ctime_by_userid(userid)
            messages = data_message_system_content_mysql.get_system_message_by_regtime(regtime)
            messageid_list = [item['messageid'] for item in messages]
            recived_messageid_list = data_message_system_status_mysql \
                .get_system_message_status_by_userid_status(userid, 1)
            unrecived_messageid_list = list(set(messageid_list)
                                            .difference(set(recived_messageid_list)))
            unrecived_message_list = [item for item in messages if item['messageid'] in unrecived_messageid_list]

            unrecived_message_item_list = []
            for messageid in unrecived_messageid_list:
                item = {
                    'userid': userid,
                    'messageid': messageid,
                    'status': 1
                }
                unrecived_message_item_list.append(item)
            if data_message_system_status_mysql.add_system_message_status_item_by_item_list(unrecived_message_item_list):
                res = {'idx': self.ss_idx, 'ret': 0, 'msg': 'ok', 'res': unrecived_message_list }
                self.write(json.dumps(res))
                self.finish()
                return

        except Exception as e:
            log.exp(e)
            self._generate_res(1, etc.err_500, 'system_mes')
            return

# class SystemMessageDelHandler(BaseHandler):
#     @ApiHost
#     def post(self):
#         userid = self.ss_user['userid']
#
#         try:
#             if not data_message_system_mysql\
#                     .delete_message_system_by_userid(userid):
#                 self._generate_res(1, '删除失败', 'del_message_system')
#                 return
#
#             ret = {
#                 'idx': self.ss_idx,
#                 'ret': 0,
#                 'res': {},
#                 'msg': 'ok',
#             }
#
#             self.write(json.dumps(ret))
#             self.finish()
#             return
#
#         except Exception as e:
#             log.exp(e)
#             self._generate_res(1, etc.err_500, 'system_mes_del')
#             return

class DelAllSystemMessageHandler(BaseHandler):
    @ApiHost
    def post(self, *args, **kwargs):
        userid = self.current_user.get('userid', None)
        if userid is None:
            log.w('params fetching error')
            res = {'idx': self.ss_idx, 'ret': 1, 'msg': etc.err_500, 'res': {}}
            self.write(json.dumps(res))
            self.finish()
            return
        item = {'status': 2}
        if data_message_system_status_mysql.update_system_message_status_by_userid(userid, item):
            res = {'idx': self.ss_idx, 'ret': 0, 'msg': '删除成功', 'res': {}}
            self.write(json.dumps(res))
            self.finish()
            return
        else:
            res = {'idx': self.ss_idx, 'ret': 1, 'msg': '删除失败', 'res': {}}
            self.write(json.dumps(res))
            self.finish()
            return

class UserMessageHandler(BaseHandler):
    @ApiHost
    def post(self):
        userid = self.ss_user['userid']
        begin = self.ss_params.get('begin', 0)
        limit = self.ss_params.get('limit', 20)

        try:
            messages = data_message_user_mysql\
                .get_message_user_by_userid(userid, begin, limit)

            peer_id_list = [m['peerid'] for m in messages]

            user_brief_map = data_user_brief_mysql\
                .get_user_brief_map_by_userid_list(peer_id_list)

            for message in messages:
                peer_id = message['peerid']
                message['user'] = user_brief_map[peer_id]

            ret = {
                'idx': self.ss_idx,
                'ret': 0,
                'res': messages,
                'msg': "ok"
            }

            self.write(json.dumps(ret))
            self.finish()
            return

        except Exception as e:
            log.exp(e)
            self._generate_res(1, etc.err_500, 'user_message')
            return


class UserMessageAddHandler(BaseHandler):
    @ApiHost
    def post(self):
        userid = self.ss_user['userid']
        peerid = self.ss_params.get('peerid')
        content = self.ss_params.get('content')

        if not (peerid and content):
            log.w('params fetching error')
            res = {'idx': self.ss_idx, 'ret': 1, 'msg': etc.err_500, 'res': {}}
            self.write(json.dumps(res))
            self.finish()
            return

        try:
            if not data_message_user_mysql.add_message_user_item({
                'userid': userid,
                'peerid': peerid,
                'content': content,
            }):
                self._generate_res(1, '新建失败', 'add_message_user')
                return

            ret = {
                'idx': self.ss_idx,
                'ret': 0,
                'res': {},
                'msg': 'ok',
            }

            self.write(json.dumps(ret))
            self.finish()
            return

        except Exception as e:
            log.exp(e)
            self._generate_res(1, etc.err_500, 'use')
            return


class UserMessageDelHandler(BaseHandler):
    @ApiHost
    def post(self):
        userid = self.ss_user['userid']

        try:
            if not data_message_user_mysql.delete_message_user_by_userid(userid):
                self._generate_res(1, '删除失败', 'del_message_user')
                return

            ret = {
                'idx': self.ss_idx,
                'ret': 0,
                'res': {},
                'msg': 'ok',
            }

            self.write(json.dumps(ret))
            self.finish()
            return

        except Exception as e:
            log.exp(e)
            self._generate_res(1, etc.err_500, 'user_mes_del')
            return


class PetMessageHandler(BaseHandler):
    @ApiHost
    def post(self):
        userid = self.ss_user['userid']
        begin = self.ss_params.get('begin', 0)
        limit = self.ss_params.get('limit', 20)

        try:
            messages = data_message_pet_mysql\
                .get_message_pet_by_userid(userid, begin, limit)
            peer_id_list = [m['peerid'] for m in messages]

            user_brief_map = data_user_brief_mysql\
                .get_user_brief_map_by_userid_list(peer_id_list)

            for message in messages:
                peer_id = message['peerid']
                message['user'] = user_brief_map[peer_id]

            ret = {
                'idx': self.ss_idx,
                'ret': 0,
                'res': messages,
                'msg': "ok"
            }

            self.write(json.dumps(ret))
            self.finish()
            return

        except Exception as e:
            log.exp(e)
            self._generate_res(1, etc.err_500, 'user_message')
            return


class PetMessageAddHandler(BaseHandler):
    @ApiHost
    def post(self):
        userid = self.ss_user['userid']
        peerid = self.ss_params.get('peerid')
        content = self.ss_params.get('content')

        if not (peerid and content):
            log.w('params fetching error')
            res = {'idx': self.ss_idx, 'ret': 1, 'msg': etc.err_500, 'res': {}}
            self.write(json.dumps(res))
            self.finish()
            return

        mtype = 1   # TODO: 目前全部是1
        if data_message_pet_mysql.get_message_pet_today_by_userid_mtype(peerid, userid, mtype):
            log.w('pet existed')
            res = {'idx': self.ss_idx, 'ret': 0, 'msg': "今天的招呼打完了", 'res': {}}
            self.write(json.dumps(res))
            self.finish()
            return

        try:
            if not data_message_pet_mysql.add_message_pet_item({
                'userid': userid,
                'peerid': peerid,
                'content': content,
            }):
                self._generate_res(1, '新建失败', 'add_message_pet')
                return

            ret = {
                'idx': self.ss_idx,
                'ret': 0,
                'res': {},
                'msg': 'ok',
            }

            self.write(json.dumps(ret))
            self.finish()
            return

        except Exception as e:
            log.exp(e)
            self._generate_res(1, etc.err_500, 'pet_msg_add')
            return


class PetMessageDelHandler(BaseHandler):
    @ApiHost
    def post(self):
        userid = self.ss_user['userid']

        try:
            if not data_message_pet_mysql.delete_message_pet_by_userid(userid):
                self._generate_res(1, '删除失败', 'del_message_pet')
                return

            ret = {
                'idx': self.ss_idx,
                'ret': 0,
                'res': {},
                'msg': 'ok',
            }

            self.write(json.dumps(ret))
            self.finish()
            return

        except Exception as e:
            log.exp(e)
            self._generate_res(1, etc.err_500, 'pet_mes_del')
            return


class NoteLikeHandler(BaseHandler):
    @ApiHost
    def post(self):
        userid = self.ss_user['userid']
        begin = self.ss_params.get('begin', 0)
        limit = self.ss_params.get('limit', 20)

        try:
            res_list = []

            # TODO: 优化
            note_like_list = data_topic_note_like_mysql\
                .get_note_like_by_followed_userid(userid, begin, limit)

            noteid_list = []
            userid_list = []
            for n in note_like_list:
                noteid_list.append(n['noteid'])
                userid_list.append(n['userid'])

            note_img_list = data_topic_note_img_mysql\
                .get_topic_note_img_by_noteid_list(noteid_list)

            all_imgid_list = []
            note_img_list_map = {}
            for item in note_img_list:
                if item['imgid']:
                    all_imgid_list.append(item['imgid'][0])
                    note_img_list_map[item['noteid']] =\
                        (item['imgid'][0], len(item['imgid']))
                else:
                    note_img_list_map[item['noteid']] = ('', 0)

            note_img_map = data_img_base_mysql\
                .get_img_url_by_imgid_list(all_imgid_list)
            note_topic_map = data_topic_note_mysql\
                .get_note_topic_map_by_noteid_list(noteid_list)

            topicid_list = note_topic_map.values()

            topic_dict = data_topic_title_mysql\
                .get_topic_title_dict_by_topicid_list(topicid_list)

            user_brief_map = data_user_brief_mysql\
                .get_user_brief_map_by_userid_list(userid_list)

            for note_like in note_like_list:
                tmp_noteid = note_like['noteid']
                tmp_userid = note_like['userid']
                tmp_img = note_img_map.get(note_img_list_map[note_like['noteid']][0], '')
                res_list.append({
                    'noteid': tmp_noteid,
                    'imglink': get_300_size_imglink(tmp_img) if tmp_img else '',
                    'imgcount': note_img_list_map[note_like['noteid']][1],
                    'topic': topic_dict[note_topic_map[tmp_noteid]],
                    'user': user_brief_map[tmp_userid],
                    'ctime': note_like['ctime'],
                })

            ret = {
                'idx': self.ss_idx,
                'ret': 0,
                'res': res_list,
                'msg': "ok"
            }

            self.write(json.dumps(ret))
            self.finish()
            return

        except Exception as e:
            log.exp(e)
            self._generate_res(1, etc.err_500, 'user_message')
            return
